<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>生产进度监控</span>
        </div>
      </template>

      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="90px">
        <el-form-item label="产品" prop="productId">
          <el-select v-model="queryParams.productId" placeholder="请选择产品" clearable>
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="批次状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择批次状态" clearable>
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="生产看板" name="dashboard">
          <div class="dashboard-container">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-card class="dashboard-card">
                  <template #header>
                    <div class="dashboard-card-header">
                      <span>生产概览</span>
                    </div>
                  </template>
                  <div class="dashboard-stat">
                    <el-row>
                      <el-col :span="12">
                        <el-statistic title="计划批次" :value="dashboard.plannedCount"></el-statistic>
                      </el-col>
                      <el-col :span="12">
                        <el-statistic title="生产中批次" :value="dashboard.inProgressCount"></el-statistic>
                      </el-col>
                    </el-row>
                    <el-row style="margin-top: 20px;">
                      <el-col :span="12">
                        <el-statistic title="已完成批次" :value="dashboard.completedCount"></el-statistic>
                      </el-col>
                      <el-col :span="12">
                        <el-statistic title="延期批次" :value="dashboard.delayedCount" value-style="color: #ff4949;"></el-statistic>
                      </el-col>
                    </el-row>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="dashboard-card">
                  <template #header>
                    <div class="dashboard-card-header">
                      <span>生产效率</span>
                    </div>
                  </template>
                  <div class="dashboard-stat">
                    <el-progress type="dashboard" :percentage="dashboard.completionRate" :color="getDashboardColor(dashboard.completionRate)">
                      <template #default="{ percentage }">
                        <span class="percentage-value">{{ percentage }}%</span>
                        <span class="percentage-label">完成率</span>
                      </template>
                    </el-progress>
                    <div class="progress-extra-info">
                      <div>计划产量: {{ dashboard.plannedQuantity }}</div>
                      <div>实际产量: {{ dashboard.actualQuantity }}</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card class="dashboard-card">
                  <template #header>
                    <div class="dashboard-card-header">
                      <span>批次状态分布</span>
                    </div>
                  </template>
                  <div class="chart-wrapper">
                    <div id="statusChart" ref="statusChart" style="width: 100%; height: 200px;"></div>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <el-divider></el-divider>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-card class="dashboard-card">
                  <template #header>
                    <div class="dashboard-card-header">
                      <span>延期风险预警</span>
                    </div>
                  </template>
                  <el-table v-loading="loading" :data="warningList" border>
                    <el-table-column label="批次号" align="center" prop="batchCode" />
                    <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
                    <el-table-column label="计划完成日期" align="center" prop="plannedEndDate">
                      <template #default="scope">
                        <span>{{ parseTime(scope.row.plannedEndDate, '{y}-{m}-{d}') }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="预计完成日期" align="center" prop="estimatedEndDate">
                      <template #default="scope">
                        <span>{{ parseTime(scope.row.estimatedEndDate, '{y}-{m}-{d}') }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="延期天数" align="center" prop="delayDays">
                      <template #default="scope">
                        <el-tag type="danger" v-if="scope.row.delayDays > 0">延期{{ scope.row.delayDays }}天</el-tag>
                        <el-tag type="warning" v-else-if="scope.row.delayDays === 0">即将延期</el-tag>
                        <el-tag type="success" v-else>正常</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="当前进度" align="center" prop="progress">
                      <template #default="scope">
                        <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row)"></el-progress>
                      </template>
                    </el-table-column>
                    <el-table-column label="风险等级" align="center" prop="riskLevel">
                      <template #default="scope">
                        <el-tag :type="getRiskLevelType(scope.row.riskLevel)">
                          {{ getRiskLevelText(scope.row.riskLevel) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="120">
                      <template #default="scope">
                        <el-button 
                          link type="primary" 
                          icon="View" 
                          @click="viewBatchDetail(scope.row)"
                        >查看</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <el-tab-pane label="甘特图" name="gantt">
          <div class="gantt-container">
            <div class="gantt-header">
              <span class="legend">
                <span class="legend-item">
                  <span class="legend-color" style="background-color: #67C23A;"></span>
                  <span>计划时间</span>
                </span>
                <span class="legend-item">
                  <span class="legend-color" style="background-color: #409EFF;"></span>
                  <span>实际时间</span>
                </span>
                <span class="legend-item">
                  <span class="legend-color" style="background-color: #F56C6C;"></span>
                  <span>延期</span>
                </span>
              </span>
            </div>
            <div class="gantt-wrapper">
              <div id="ganttChart" ref="ganttChart" style="width: 100%; height: 500px;"></div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { parseTime } from '@/utils/ruoyi'
// 注释掉原有API导入
// import { getProductionProgress } from '@/api/qep/production'
// import { listProduct } from '@/api/qep/product'
import * as echarts from 'echarts'
// 导入mock数据
import { progressMonitorMockData } from '@/mock/production'

const router = useRouter()

// 遮罩层
const loading = ref(false)
// 选中标签
const activeName = ref('dashboard')
// 日期范围
const dateRange = ref([])
// 产品选项
const productOptions = ref([])
// 批次状态图表
let statusChartInstance = null
// 甘特图表
let ganttChartInstance = null
// 图表容器
const statusChart = ref(null)
const ganttChart = ref(null)
// 查询参数
const queryParams = reactive({
  productId: undefined,
  status: undefined,
  startDate: undefined,
  endDate: undefined
})

// 看板数据
const dashboard = reactive({
  plannedCount: 0,
  inProgressCount: 0,
  completedCount: 0,
  delayedCount: 0,
  completionRate: 0,
  plannedQuantity: 0,
  actualQuantity: 0
})

// 预警列表
const warningList = ref([])
// 甘特图数据
const ganttData = ref([])

// 批次状态选项
const statusOptions = ref([])

// 监听日期范围变化
watch(dateRange, (newVal) => {
  queryParams.startDate = newVal && newVal.length > 0 ? newVal[0] : undefined
  queryParams.endDate = newVal && newVal.length > 0 ? newVal[1] : undefined
})

// 获取风险等级类型
const getRiskLevelType = (level) => {
  if (level === 'HIGH') return 'danger'
  if (level === 'MEDIUM') return 'warning'
  if (level === 'LOW') return 'info'
  return 'success'
}

// 获取风险等级文本
const getRiskLevelText = (level) => {
  const levelMap = {
    'HIGH': '高风险',
    'MEDIUM': '中风险',
    'LOW': '低风险',
    'NONE': '无风险'
  }
  return levelMap[level] || level
}

// 获取进度状态
const getProgressStatus = (row) => {
  if (row.delayDays > 0) return 'exception'
  if (row.progress >= 100) return 'success'
  return ''
}

// 获取看板颜色
const getDashboardColor = (value) => {
  if (value < 40) return '#F56C6C'
  if (value < 70) return '#E6A23C'
  return '#67C23A'
}

// 初始化图表
const initCharts = async () => {
  // 使用nextTick确保DOM已完全渲染
  await nextTick();
  
  // 延迟初始化图表，给DOM足够的时间渲染
  setTimeout(() => {
    // 销毁现有图表实例
    if (statusChartInstance) {
      statusChartInstance.dispose();
    }
    if (ganttChartInstance) {
      ganttChartInstance.dispose();
    }

    // 创建新图表实例，确保DOM元素存在且有尺寸
    if (statusChart.value && statusChart.value.offsetHeight > 0) {
      statusChartInstance = echarts.init(statusChart.value);
    }
    if (ganttChart.value && ganttChart.value.offsetHeight > 0) {
      ganttChartInstance = echarts.init(ganttChart.value);
    }
    
    // 渲染数据
    renderStatusChart();
    renderGanttChart();
  }, 300);
}

// 渲染状态图表
const renderStatusChart = () => {
  if (!statusChartInstance) {
    if (statusChart.value && statusChart.value.offsetHeight > 0) {
      statusChartInstance = echarts.init(statusChart.value);
    } else {
      return;
    }
  }

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      data: progressMonitorMockData.statusDistribution.map(item => item.name)
    },
    series: [
      {
        name: '批次状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: progressMonitorMockData.statusDistribution.map(item => {
          let color = '#409EFF';
          switch(item.name) {
            case '计划中': color = '#E6A23C'; break;
            case '生产中': color = '#409EFF'; break;
            case '已完成': color = '#67C23A'; break;
            case '已延期': color = '#F56C6C'; break;
            case '已取消': color = '#909399'; break;
          }
          return {
            value: item.value,
            name: item.name,
            itemStyle: { color }
          };
        })
      }
    ]
  }

  statusChartInstance.setOption(option)
}

// 渲染甘特图
const renderGanttChart = () => {
  if (!ganttChartInstance) {
    if (ganttChart.value && ganttChart.value.offsetHeight > 0) {
      ganttChartInstance = echarts.init(ganttChart.value);
    } else {
      return;
    }
  }

  // 准备甘特图数据
  const categories = ['计划开始', '计划结束', '实际开始', '预计结束'];
  const series = [];
  const data = progressMonitorMockData.ganttData;

  // 处理日期数据
  data.forEach(batch => {
    const seriesData = [];
    batch.values.forEach((item, index) => {
      seriesData.push({
        name: categories[index],
        value: [
          new Date(item.x).getTime(),
          index,
          categories[index]
        ]
      });
    });

    // 添加到系列中
    series.push({
      name: batch.name,
      type: 'scatter',
      symbolSize: 20,
      data: seriesData
    });

    // 添加连接线
    series.push({
      name: batch.name + ' 连接线',
      type: 'line',
      data: [
        [new Date(batch.values[0].x).getTime(), 0],
        [new Date(batch.values[1].x).getTime(), 1]
      ],
      lineStyle: {
        color: '#67C23A'
      },
      showSymbol: false
    });

    // 如果有实际开始和预计结束
    if (batch.values.length >= 4) {
      series.push({
        name: batch.name + ' 实际连接线',
        type: 'line',
        data: [
          [new Date(batch.values[2].x).getTime(), 2],
          [new Date(batch.values[3].x).getTime(), 3]
        ],
        lineStyle: {
          color: '#409EFF'
        },
        showSymbol: false
      });

      // 如果有延期，添加延期标记
      if (new Date(batch.values[3].x) > new Date(batch.values[1].x)) {
        series.push({
          name: batch.name + ' 延期标记',
          type: 'line',
          data: [
            [new Date(batch.values[1].x).getTime(), 1],
            [new Date(batch.values[3].x).getTime(), 3]
          ],
          lineStyle: {
            color: '#F56C6C',
            type: 'dashed'
          },
          showSymbol: false
        });
      }
    }
  });

  // 甘特图配置
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        if (params.seriesType === 'scatter') {
          return params.seriesName + '<br/>' + params.data.name + ': ' + 
                 new Date(params.data.value[0]).toLocaleDateString();
        }
        return '';
      }
    },
    grid: {
      left: 100,
      right: 20,
      top: 20,
      bottom: 30
    },
    xAxis: {
      type: 'time',
      axisLabel: {
        formatter: '{yyyy}-{MM}-{dd}'
      }
    },
    yAxis: {
      type: 'category',
      data: data.map(item => item.name),
      inverse: true
    },
    series: series
  };

  ganttChartInstance.setOption(option);
}

// 使用mock数据获取产品和状态选项
const getOptions = () => {
  productOptions.value = progressMonitorMockData.productOptions;
  statusOptions.value = progressMonitorMockData.statusOptions;
}

// 使用mock数据获取看板数据
const getDashboardData = () => {
  loading.value = true;
  
  // 模拟API调用延迟
  setTimeout(() => {
    // 复制看板数据
    Object.assign(dashboard, progressMonitorMockData.dashboard);
    
    // 设置预警列表
    warningList.value = progressMonitorMockData.warningList;
    
    // 渲染状态图表
    renderStatusChart();
    
    loading.value = false;
  }, 500);
}

// 使用mock数据获取甘特图数据
const getGanttData = () => {
  loading.value = true;
  
  // 模拟API调用延迟
  setTimeout(() => {
    // 设置甘特图数据
    ganttData.value = progressMonitorMockData.ganttData;
    
    // 渲染甘特图
    renderGanttChart();
    
    loading.value = false;
  }, 500);
}

// 处理标签点击
const handleTabClick = () => {
  if (activeName.value === 'dashboard') {
    getDashboardData();
  } else if (activeName.value === 'gantt') {
    getGanttData();
  }
}

// 搜索按钮操作
const handleQuery = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.startDate = dateRange.value[0]
    queryParams.endDate = dateRange.value[1]
  } else {
    queryParams.startDate = undefined
    queryParams.endDate = undefined
  }
  
  // 根据当前活动标签重新加载数据
  handleTabClick();
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryParams.productId = undefined
  queryParams.status = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  
  // 重新加载数据
  handleTabClick();
}

// 查看批次详情
const viewBatchDetail = (row) => {
  router.push({ path: '/production/batch/detail', query: { batchCode: row.batchCode } });
}

// 监听窗口大小变化，重新调整图表大小
const resizeHandler = () => {
  if (statusChartInstance) {
    statusChartInstance.resize()
  }
  if (ganttChartInstance) {
    ganttChartInstance.resize()
  }
}

onMounted(() => {
  // 获取选项数据
  getOptions();
  
  // 初始化图表
  initCharts();
  
  // 加载看板数据
  getDashboardData();
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', resizeHandler);
})

onBeforeUnmount(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', resizeHandler);
  
  // 销毁图表实例
  if (statusChartInstance) {
    statusChartInstance.dispose();
    statusChartInstance = null;
  }
  if (ganttChartInstance) {
    ganttChartInstance.dispose();
    ganttChartInstance = null;
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dashboard-container {
  position: relative;
}

.dashboard-card {
  margin-bottom: 20px;
}

.dashboard-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dashboard-stat {
  padding: 10px;
  text-align: center;
}

.progress-extra-info {
  margin-top: 10px;
  text-align: center;
  color: #606266;
}

.percentage-value {
  display: block;
  font-size: 28px;
  margin-top: 10px;
}

.percentage-label {
  display: block;
  font-size: 12px;
  color: #909399;
}

.gantt-container {
  position: relative;
}

.gantt-header {
  margin-bottom: 20px;
}

.gantt-wrapper {
  margin-bottom: 20px;
  height: 500px; /* 确保图表容器有固定高度 */
}

.chart-wrapper {
  margin-bottom: 20px;
  height: 200px; /* 确保图表容器有固定高度 */
}

.legend {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.legend-color {
  display: inline-block;
  width: 16px;
  height: 16px;
  margin-right: 5px;
  border-radius: 2px;
}

.el-divider {
  margin: 20px 0;
}
</style> 